<template>
	<view>
		<view class="pageBox" v-if="!data.isband && !data.heartError.show">
			<uv-image :src="data.liveInfo?.material_cover_full_url" width="100%" height="300rpx" mode="widthFix" v-if="data.showCover" />
			<view id="mui-player" class="live-mui" v-show="data.liveInfo.status === 1 && !data.showCover"></view>
			<view class="live-info">
				<view class="name">{{data.liveInfo?.live_name}}</view>
				<view class="time">{{data.liveInfo?.start_time}}</view>
				<view class="tips" v-if="data.showStartBtn">
					<uv-icon name="warning" size="22" color="#63a103" />
					<view>{{data.liveInfo?.tip_message}}</view>
				</view>
			</view>

			<view class="question" v-if="data.showSumbit">
				<view class="question-item" v-for="(item,index) in data.questionList" :key="item.id">
					<view class="questionQ">
						<text> 题目 </text>:{{item.content}}
					</view>
					<view :class="el.check ? 'questionA on' : 'questionA' " v-for="(el,idx) in item.option_item"
						:key="idx" @click="selectAn(index,item.live_award_id,item.id,el.option,idx)">
						{{el.option}}. {{el.content}}
						<view v-if="data.checkIn[index][idx] && el.check && data.showAnswer">
							<uv-icon name="checkmark" color="#03830d" size="20" v-if="el.isTrue"></uv-icon>
							<uv-icon name="close" color="#cb0000" size="20" v-else></uv-icon>
						</view>
					</view>
				</view>
			</view>
			<view class="btmTips" v-if="data.liveInfo.status === 0">
				<span>倒计时:</span>
				<span v-if="days">{{ days }}:</span>
				<span>{{ hours }}:</span>
				<span>{{ minutes }}:</span>
				<span>{{ seconds }}</span>
			</view>
			<block v-if="data.liveInfo.status === 1">
				<view class="btmTips" @click="startPlay" v-if="data.showStartBtn">观看直播</view>
				<view class="btmTips"
					v-if="data.liveInfo.award_trigger_duration && !data.showStartBtn && data.isSubmit">
					累计观看{{ data.totalTime }}分钟，才可以答题</view>
				<!-- <view class="btmTips" v-if="data.quesCount">答题倒计时{{data.award_trigger_duration}}秒</view> -->
				<view class="btmTips" @click="sumbitAnswer"
					v-if="data.showSumbit && data.isSubmit && data.answersDisable">提交答案</view>
			</block>
		</view>

		<!-- 未正常绑定 -->
		<view class="bind-error" v-if="data.isband && !data.heartError.show">
			<uv-icon name="error-circle" color="#fc4631" size="40"></uv-icon>
			<view class="red">{{ data.bindError }}</view>
			<view class="tips" v-if="data.otherName">已绑定商户：{{ data.otherName }}</view>
		</view>

		<!-- 心跳检测到视频中断或异常 -->
		<view class="bind-error" v-if="data.heartError.show">
			<uv-icon name="error-circle" color="#fc4631" size="40"></uv-icon>
			<view class="red">{{ data.heartError.msg }}</view>
		</view>

		<uv-toast ref="toastLayer"></uv-toast>

		<!-- 奖励弹窗效果   新子-->
		<uv-popup ref="RewardLayer" mode="center" :customStyle="modalStyle" :closeOnClickOverlay="false">
			<view class="custom-modal-content" @click="getAward">
				<image src="/static/redPacket.png" mode="widthFix" class="modal-image" />
				<view class="modal-text">
					<text class="i">¥</text>{{data.awardNum}}<text class="i">元</text>
				</view>
			</view>
		</uv-popup>
		<!-- 奖励弹窗效果   新子 end-->
	</view>
</template>


<script setup>
	import 'mui-player/dist/mui-player.min.css'
	import MuiPlayer from 'mui-player';
	import dayjs from 'dayjs';
	import Hls from 'hls.js'
	import {
		bindLive,
		getlive,
		heartbeat,
		questionList,
		questionAn,
		getStatus,
		sendRedPacketApi,
		getTimeIndex
	} from '@/api';
	import {
		nextTick,
		pushScopeId,
		watch
	} from 'vue';

	const days = ref(0);
	const hours = ref(0);
	const minutes = ref(0);
	const seconds = ref(0);
	const toastLayer = ref(null);
	const data = reactive({
		code: null, //企业code
		bindError: '',
		once: true,
		liveNo: null,
		mid: null,
		mp: null,
		isband: false,
		otherName: '',
		
		showCover: true,
		showStartBtn: true,
		liveInfo: {},
		currentTime: 0, //跳转到直播指定时间
		totalTime: 0,
		allQuestionList: [],
		answers: [],
		answersDisable: true,
		showAnswer: false, //到答题时间标记
		isSubmit: false, //第一次提交标记
		showSumbit: false, //提交答案按钮
		// 答题倒计时-需求有变动
		// award_trigger_duration:1000,

		heartError: { //心跳异常情况处理
			show: false,
			msg: ''
		},

		live_award_id: '',
		checkIn: [],
		awardNum: 0, //新子有改动
	})
	onLoad((option) => {
		console.log('live index111',option)
		data.code = option.company_code
		data.liveNo = option.live_no
		data.mid = option.mid
		uni.showLoading()
		const token = uni.getStorageSync('token')
		if (token) {
			if (data.code) {
				bindLiveUser()
			} else {
				getLiveDetail()
			}
		} else {
			setTimeout(() => {
				if (data.code) {
					bindLiveUser()
				} else {
					getLiveDetail()
				}
			}, 500);
		}
	})
	onShow(async () => {
		if ((!data.once) && (!data.showStartBtn)) {
			let now = await getServeIndex()
			let start = new Date(data.liveInfo.start_time).getTime()
			data.currentTime = Math.ceil(((now - start) / 1000))
			setTimeout(() => {
				data.mp.video().currentTime = data.currentTime
				data.mp.video().muted=false
				intervalId = setInterval(getHeartbeat, 5000);
			}, 500)
		}
		// getLiveDetail()
		// data.test2++
		// if(!data.showStartBtn){
		// 	startPlay()
		// }
	})
	onHide(() => {
		data.once = false
		setTimeout(() => {
			data.mp.video().muted=true
		}, 500)
		clearInterval(intervalId); // 组件销毁时清除计时器，防止内存泄漏
	})
	onUnmounted(() => {
		data.mp.destroy();
		clearInterval(intervalId); // 组件销毁时清除计时器，防止内存泄漏
	})
	onUnload(() => {
		data.mp.destroy();
		clearInterval(intervalId); // 组件销毁时清除计时器，防止内存泄漏
	})
	//倒计时
	let intervalId
	let qusIntervalId
	const calculateTimeLeft = () => {
		let time = data.liveInfo.start_time
		if (!time) return

		// const futureDate = new Date('2025-06-30T11:33:00');
		const futureDate = new Date(time.replace(" ", "T"));
		const difference = futureDate - new Date();
		if (difference > 0) {
			let hh = Math.floor((difference / (1000 * 60 * 60)) % 24);
			let mm = Math.floor((difference / (1000 * 60)) % 60);
			let ss = Math.floor((difference / 1000) % 60);

			days.value = Math.floor((difference / (1000 * 60 * 60 * 24)));
			hours.value = Number(hh) < 10 ? '0' + hh : hh
			minutes.value = Number(mm) < 10 ? '0' + mm : mm
			seconds.value = Number(ss) < 10 ? '0' + ss : ss
		} else {
			clearInterval(intervalId); // 停止计时器，因为时间已经结束
			data.liveInfo.status = 1
			data.liveInfo.tip_message = '当前直播进行中，请点击按钮进入观看。'
			initPlayer()
		}
	};
	//绑定
	const bindLiveUser = () => {
		const params = {
			openid: uni.getStorageSync('openid'),
			live_no: data.liveNo,
			mid: data.mid
		}
		bindLive(params).then(res => {
			uni.hideLoading()
			if (res.code === 200001) {
				uni.setStorageSync('token', res.data.access_token)
				uni.setStorageSync('mid', data.mid)
				uni.setStorageSync('companyCode', data.code)

				getLiveDetail()
			} else if (res.code > 500213) {
				data.isband = true
				data.bindError = res.message
			} else if (res.code === 500212) {
				data.bindError = '您已绑定其他用户，无法再绑定该用户！'
				data.isband = true
				data.otherName = res.data.merchant_name
			} else if (res.code === 400200) {
				// goIndex(res.message)
			} else {
				toastLayer.value.show({
					type: 'error',
					message: res.message
				})
			}
		}).catch(error => {
			console.error('绑定直播失败:', error);
		});
	}
	//直播信息
	const getLiveDetail = () => {
		getlive({
			live_no: data.liveNo
		}).then(res => {
			if (res.code == 200001) {
				data.liveInfo = res.data
				data.totalTime = Math.floor(data.liveInfo.award_trigger_duration / 60)
				if (data.liveInfo.status == 0) {
					intervalId = setInterval(calculateTimeLeft, 1000); // 开播倒计时，每秒更新一次时间
				} else if (data.liveInfo.status == 1) {
					initPlayer() //直播中
				} else if (data.liveInfo.status == 2) {
					uni.showModal({
						title: '提示',
						content: '直播已经结束',
						showCancel: false,
						confirmText: '',
						success: function(res) {}
					});
				}
			} else {
				const params = {
					type: 'error',
					title: '默认主题',
					message: res.message
				}
				toastLayer.value.show({
					...params,
					complete() {
						// console.log('toast')
					}
				})
			}
		}).catch(error => {
			const params = {
				type: 'error',
				title: '',
				message: error
			}
			toastLayer.value.show({
				params
			})
		});
	}
	//初始化播放器
	const initPlayer = () => {
		data.mp = new MuiPlayer({
			container: '#mui-player',
			src: data.liveInfo.material_video_full_url,
			loop: false,
			parse: {
				type: 'hls',
				loader: Hls,
			},
		})
		let videoTag = document.getElementsByTagName('video')[0]
		videoTag.setAttribute('webkit-playsinline', 'true');
		videoTag.setAttribute('playsinline', 'true');
		nextTick(() => {
			data.mp.on('ready', function(event) {
				let _video = data.mp.video();
				_video.addEventListener("play", function(e) {
					//播放事件
					if (data.showStartBtn) {
						data.mp.video().pause()
					}
				});
				_video.addEventListener("pause", function(e) {
					//暂停事件
					if (!data.showStartBtn) {
						data.mp.video().play()
					}
				});
				_video.addEventListener("ended", function(e) {
					clearInterval(intervalId)
					data.liveInfo.status == 2
					data.showCover = true
					data.mp.destroy();
					uni.showModal({
						title: '提示',
						content: '直播已经结束',
						showCancel: false,
						confirmText: '',
						success: function(res) {}
					});
				});
			});
		})
	}
	//获取服务器时间戳
	const getServeIndex = () => {
		return new Promise((resolve, reject) => {
			getTimeIndex().then(res => {
				resolve(res.data.server.current_time)
			})
		});
	}
	//开启播放
	const startPlay = async () => {
		let now = await getServeIndex()
		let start = new Date(data.liveInfo.start_time).getTime()
		data.currentTime = Math.ceil(((now - start) / 1000))
		if (data.currentTime > data.liveInfo.duration) {
			data.liveInfo.material_video_full_url = ''
			data.liveInfo.status = 2
			goIndex()
			return
		}
		data.showStartBtn = false
		data.showCover = false
		data.mp.video().play()
		data.mp.video().currentTime = data.currentTime

		if (data.liveInfo.is_need_answer === 1) {
			getQsList()
		}
		// 播放心跳,每5秒更新一次时间
		intervalId = setInterval(getHeartbeat, 5000);
	}
	const getHeartbeat = () => {
		heartbeat({
			live_no: data.liveNo
		}).then(res => {
			if (res.code === 200001) {
				//是否视频下架
				if (res.data.live_is_down) {
					data.liveInfo.material_video_full_url = ''
					data.liveInfo.status = 2
					data.mp.video().src = ''
					clearInterval(intervalId)

					uni.showModal({
						title: '提示',
						content: '直播已经已下架,点击确定跳回首页',
						showCancel: false,
						success: function(res) {
							if (res.confirm) {
								uni.navigateTo({
									url: '/pages/index'
								})
							}
						}
					});
				}

				if (res.data.watch.watch_duration > data.liveInfo.award_trigger_duration) {
					data.showSumbit = true
				}
				//设置显示的红包金额-----新子
				if (res.data.award_amount) {
					data.awardNum = res.data.award_amount;
				}
				if (res.data.can_pop_award_tip) {
					console.log('红包红包')
					hintReward();
				}
				//设置显示的红包金额-----新子 end
			} else if (res.code === 400203) {
				const params = {
					type: 'error',
					title: '',
					message: res.message
				}
				toastLayer.value.show({
					params
				})
				//暂停直播
				data.liveInfo.material_video_full_url = ''
				data.liveInfo.status = 2
				data.mp.video().src = ''
				clearInterval(intervalId)
			} else if (res.code === 500501) {
				if (res.data.err_flag > 2) {
					data.heartError.show = true
					data.heartError.msg = res.data.msg
				} else {
					// toastLayer.value.show({type: 'error',duration: 10000,message: res.data.msg})
					goIndex()
				}
				//暂停直播
				data.liveInfo.material_video_full_url = ''
				data.liveInfo.status = 2
				data.mp.video().src = ''
				clearInterval(intervalId)
			}
		}).catch(error => {
			const params = {
				type: 'error',
				title: '默认主题',
				message: res.message
			}
			toastLayer.value.show({
				params
			})
		});
	}
	const getQsList = () => {
		const params = {
			live_id: data.liveInfo.live_id
		}
		questionList(params).then(res => {
			if (res.data.customer_is_submit) {
				return
			}
			data.isSubmit = true
			data.questionList = res.data.question
			data.questionList.forEach(ele => {
				data.answers.push(null)
				let arr = []
				ele.option_item.forEach(el => {
					if (el.option == ele.answer) {
						el.isTrue = true
					}
					el.check = false
					arr.push(false)
				})
				data.checkIn.push(arr)
			})
		})
	}
	const selectAn = (index, live_award_id, id, answer, idx) => {
		if (!data.answersDisable) {
			return false
		}
		data.live_award_id = live_award_id
		data.answers[index] = {
			question_id: id,
			type: 'single',
			answer: answer,
		}
		data.checkIn[index][idx] = true
		data.questionList[index].option_item.forEach(item => {
			item.check = false
		})
		data.questionList[index].option_item[idx].check = true
	}
	const sumbitAnswer = () => {
		let flag = true
		data.answers.forEach(ele => {
			if (!ele) {
				flag = false
			}
		})
		if (flag) {
			let parmas = {}
			parmas.answers = data.answers
			parmas.live_id = data.liveInfo.live_id
			parmas.live_award_id = data.live_award_id
			questionAn(parmas).then(res => {
				data.answersDisable = false
				data.showAnswer = true
				data.isSubmit = false
				if (res.code == 200001) {
					uni.showToast({
						title: "答题完成",
					})
					//全对才能下发红包
					if (res.data.all_questions_correct) {
						console.log('全对，等待红包下发')
						//等待红包下发--新子
						setTimeout(() => {
							getHeartbeat();
						}, 3000);
					}
				} else {
					uni.showToast({
						title: res.message,
						icon: 'error'
					})
				}
			})
		} else {
			uni.showToast({
				title: "请答完所有题目",
				icon: 'error'
			})
		}
	}
	const goIndex = (msg) => {
		uni.showModal({
			title: '提示',
			content: msg ? msg : '直播已经结束',
			showCancel: false,
			confirmText: '',
			success: function(res) {}
		});
	}

	//---------------- 奖励相关操作  新子--------------------

	const RewardLayer = ref(null)

	const modalStyle = {
		background: 'transparent',
		boxShadow: 'none',
		borderRadius: '0',
		overflow: 'visible',
		border: 'none',
		padding: '0'
	}
	const getAward = () => {
		//通知后端红包领取状态
		RewardLayer.value.close()
		// sendRedPacketApi({live_no:data.liveNo}).then(res=>{
		// 	console.log('记录用户点击领取红包');
		// })
	}
	const hintReward = () => {
		console.log('调起新子')
		RewardLayer.value.open()
	}
</script>

<style lang="scss" scoped>
	:deep(.m-player .mini-progress .mini-play) {
		height: 0 !important;
		visibility: hidden;
	}

	page {
		background-color: #f1f1f1;
	}

	.pageBox {
		padding: 0;
		height: 100%;
		display: flex;
		flex-flow: column nowrap;

		.live-info {
			color: #333;
			padding: 40rpx;
			line-height: 60rpx;

			.name {
				font-size: 36rpx;
				font-weight: 600;
			}

			.time {
				font-size: 24rpx;
			}

			.tips {
				font-size: 28rpx;
				color: #63a103;
				margin-top: 40rpx;
				display: flex;
			}
		}

		.question {
			padding: 0 40rpx;
			max-height: calc(100vh - 780rpx);
			overflow: auto;

			.question-item {
				margin-bottom: 40rpx;

				.questionQ {
					font-size: 30rpx;
					margin-bottom: 30rpx;

					text {
						color: red;
					}
				}

				.questionA {
					margin: 10rpx 0;
					display: flex;
					justify-content: space-between;
					padding: 20rpx;
					border-radius: 10rpx;
				}

				.questionA.on {
					background: #ccc;
				}
			}
		}

		.btmTips {
			position: fixed;
			bottom: 0;
			left: 0;
			width: 100vw;
			background: #ef4636;
			text-align: center;
			padding: 40rpx 0 50rpx;
			color: #fff;

			span:first-child {
				margin-right: 10rpx;
			}
		}
	}

	.bind-error {
		text-align: center;
		padding-top: 15vh;

		.uv-icon {
			justify-content: center;
			margin-bottom: 60rpx;
		}

		.red {
			color: #fc4631;
		}

		.tips {
			font-size: 26rpx;
			padding: 50rpx 0;
		}
	}

	.videoBox {
		width: 100%;
	}

	.videoMenu {
		@extend %flex-row-center;
		color: #333;
		font-size: 26rpx;

		&_item {
			width: 50%;
			text-align: center;
			border-bottom: solid 4rpx #fff;
			padding-bottom: 20rpx;
			padding-top: 20rpx;

			&.active {
				border-bottom: solid 4rpx #fc4631;
			}
		}
	}

	.chatHome {
		flex: 1;
		background-color: #efefef;

		.bottom {
			position: fixed;
			bottom: 30rpx;
			padding: 20rpx;
			background-color: #fff;
			width: 100%;
			box-sizing: border-box;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.begun-t {
				color: green;
				font-size: 24rpx;
				font-weight: bold;
			}

			.bottom_left {
				display: flex;
				justify-content: space-between;
				background-color: #efefef;
				flex: 1;
				padding: 10rpx 20rpx;
				margin-right: 30rpx;
				border-radius: 10rpx;
				align-items: center;

				.t {
					color: #666;
					font-size: 24rpx;
				}

				.btn {
					width: fit-content;
					background: #c3c3c3;
					color: #666;
					border: none;
					border-radius: 10rpx;
					padding: 15rpx;
					font-size: 21rpx;
					line-height: 20rpx;
					font-weight: bold;
					cursor: pointer;
				}
			}
		}

		.begunCon {
			margin-top: 100rpx;
			display: flex;
			flex-flow: column nowrap;
			align-items: center;

			.word {
				text-align: center;
				margin-bottom: 20rpx;
				color: #333;

				&.grey {
					color: #999;
					font-size: 24rpx;
				}
			}

			.btn {
				width: fit-content;
				background: #ef4636;
				color: #fff;
				border: none;
				border-radius: 10rpx;
				padding: 20rpx;
				font-size: 24rpx;
				line-height: 30rpx;
				font-weight: bold;
				cursor: pointer;
				text-align: center;
				margin-top: 50rpx;
			}
		}
	}

	.questionList {
		background-color: #fff;
		border-radius: 15rpx;
		margin: 10rpx 20rpx;
		padding: 30rpx;

		.title {
			font-size: 28rpx;
			margin-bottom: 30rpx;
		}

		.option {
			font-size: 26rpx;
			color: #333;
			margin-bottom: 30rpx;
			padding: 10rpx;

			&.select {
				background-color: #36d53660;
			}

			&.close {
				background-color: #ff000050;
			}
		}

		.btn {
			width: 100%;
			background: #ef4636;
			color: #fff;
			border: none;
			border-radius: 10rpx;
			padding: 20rpx 0;
			font-size: 24rpx;
			line-height: 30rpx;
			font-weight: bold;
			cursor: pointer;
			text-align: center;
		}
	}

	.nomore {
		text-align: center;
		color: #999;
		padding: 20rpx 0;
		font-size: 24rpx;
	}

	.videoBox {
		position: relative;

		.person {
			position: absolute;
			background-color: red;
			color: #fff;
			z-index: 555;
			right: 0;
			top: 20rpx;
			padding: 10rpx;
			border-radius: 5rpx;
			font-size: 18rpx;
		}
	}

	// *****************新子
	/* 确保弹窗内容背景透明 */
	.custom-modal-content {
		position: relative;
		width: 300px;
		margin: 0 auto;
	}

	.modal-image {
		width: 100%;
		display: block;
	}

	.modal-text {
		position: absolute;
		top: 220rpx;
		left: 50%;
		transform: translate(-50%, -50%);
		color: #ff0000;
		font-size: 80rpx;
		text-align: center;
		width: 100%;

		.i {
			font-size: 50rpx;
		}
	}
</style>